<?php
$db['server'] = 'localhost';
$db['user'] = 'root';
$db['password'] = '';
$db['name'] = 'theme_editor';

$viewer = new Viewer(1);

class Viewer {
   public $width = 800;
   public $height = 600;
   public $x = 0;
   public $y = 0;

   private $theme_id = -1;
   
   /**
    * Constructor.
    * It takes in the $theme_id that it is currently working on.
    */
   public function Viewer($theme_id){
      $this->theme_id = $theme_id;
   }

   /**
    * loadIcon() generates portion of the javascript codes that loads the image of icons into the canvas.
    */
   public function loadIcon(){
      global $db;
      $conn = mysql_connect($db['server'],$db['user'],$db['password']);
      if(!$conn) die('Could not connect: ' . mysql_error());
      mysql_select_db($db['name'], $conn);

      $query = "SELECT * FROM te_icon WHERE icon_theme = " . $this->theme_id . " ORDER BY icon_id";

      $result = mysql_query($query);

      while($row = mysql_fetch_array($result)){
         ?>            canvasicon.addIcon(<?php echo $row['icon_x']; ?>,<?php echo $row['icon_y']; ?>,<?php echo $row['icon_width']; ?>,<?php echo $row['icon_height']; ?>,"<?php echo $row['icon_image']; ?>");
<?php }

      mysql_close($conn);
   }
   
   public function loadDropbox(){
      global $db;
      $conn = mysql_connect($db['server'],$db['user'],$db['password']);
      if(!$conn) die('Could not connect: ' . mysql_error());
      mysql_select_db($db['name'], $conn);

      $query = "SELECT dropboxitem_id,dropboxitem_icon,dropboxitem_name,dropboxitem_link FROM te_dropboxitem,te_icon WHERE icon_id = dropboxitem_icon AND icon_theme = " . $this->theme_id . " ORDER BY dropboxitem_icon,dropboxitem_id";
      
      $result = mysql_query($query);


      $curr_item = -1;
      $dropboxlink = "";
      echo "         var dropboxes = new Array(\n";
      $dropboxlink = "         var dropboxlinks = new Array(\n";
      while($row = mysql_fetch_array($result)){
         if($row['dropboxitem_icon']==$curr_item){
            echo ",'".$row['dropboxitem_name']."'";
            $dropboxlink .= ",'".$row['dropboxitem_link']."'";
         }else{
            if($curr_item!=-1){
               echo "),\n";
               $dropboxlink .= "),\n";
            }
            $curr_item = $row['dropboxitem_icon'];
            echo "                           new Array('".$row['dropboxitem_name']."'";
            $dropboxlink .= "                              new Array('".$row['dropboxitem_link']."'";
         }
      }
      echo ")\n";
      echo "                        );\n";
      $dropboxlink .= ")\n";
      $dropboxlink .= "                           );\n";
      echo $dropboxlink;
      mysql_close($conn);
   }

   /**
    * loadDataURL() extracts the image dataurl of the theme.
    */
   public function loadDataURL(){
      global $db;
      $conn = mysql_connect($db['server'],$db['user'],$db['password']);
      if(!$conn) die('Could not connect: ' . mysql_error());
      mysql_select_db($db['name'], $conn);

      $query = "SELECT theme_image FROM te_theme WHERE theme_id = " . $this->theme_id;
      $result = mysql_query($query);

      $row = mysql_fetch_array($result);
      echo $row['theme_image'];
      
      mysql_close($conn);
   }

   /**
    * loadIconMovement() extracts the iconmovement for the theme.
    */
   public function loadIconMovement(){
      global $db;
      $conn = mysql_connect($db['server'],$db['user'],$db['password']);
      if(!$conn) die('Could not connect: ' . mysql_error());
      mysql_select_db($db['name'], $conn);

      $query = "SELECT theme_iconmovement FROM te_theme WHERE theme_id = " . $this->theme_id;
      $result = mysql_query($query);

      $row = mysql_fetch_array($result);
      echo $row['theme_iconmovement'];
      
      mysql_close($conn);
   }

}
?><html> 
   <head> 
      <title>DEFAULT TEMPLATE</title> 
      <script type="text/javascript">
		var djConfig = {
			parseOnLoad: true
		};
	</script>
	<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js"></script>
	<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css" />
      <script type="text/javascript"> 
	  
	  	dojo.require("dijit.Menu");
         
         const CANVAS = {ICON:"canvasIcon",IMAGE:"canvasImage",DROPBOX:"canvasDropBox"};
         const DIMENSION = {X:<?php echo $viewer->x;?>,Y:<?php echo $viewer->y;?>,WIDTH:<?php echo $viewer->width;?>,HEIGHT:<?php echo $viewer->height;?>};
         
 
         var mouse={x:0,y:0,m:0,n:0};
         var current={canvas:CANVAS.ICON,mousedown:false,iconmovement:"<?php $viewer->loadIconMovement(); ?>"};
         var icons = new Array();/*
         var dropboxes = new Array(
                           new Array("Dropbox 0.0","Dropbox 0.1","Dropbox 0.2","Dropbox 0.3","Dropbox 0.4","Dropbox 0.5"),
                           new Array("Dropbox 1.0","Dropbox 1.1","Dropbox 1.2","Dropbox 1.3","Dropbox 1.4","Dropbox 1.5"),
                           new Array("Dropbox 2.0","Dropbox 2.1","Dropbox 2.2","Dropbox 2.3","Dropbox 2.4","Dropbox 2.5"),
                           new Array("Dropbox 3.0","Dropbox 3.1","Dropbox 3.2","Dropbox 3.3","Dropbox 3.4","Dropbox 3.5"),
                           new Array("Dropbox 4.0","Dropbox 4.1","Dropbox 4.2","Dropbox 4.3","Dropbox 4.4","Dropbox 4.5"),
                           new Array("Dropbox 5.0","Dropbox 5.1","Dropbox 5.2","Dropbox 5.3","Dropbox 5.4","Dropbox 5.5"),
                           new Array("Dropbox 6.0","Dropbox 6.1","Dropbox 6.2","Dropbox 6.3","Dropbox 6.4","Dropbox 6.5"),
                           new Array("Dropbox 7.0","Dropbox 7.1","Dropbox 7.2","Dropbox 7.3","Dropbox 7.4","Dropbox 7.5"),
                           new Array("Dropbox 8.0","Dropbox 8.1","Dropbox 8.2","Dropbox 8.3","Dropbox 8.4","Dropbox 8.5")
                        );*/
<?php $viewer->loadDropbox();?>         
         document.onmousedown = mouseDown;
         document.onmouseup = mouseUp;
         document.onmousemove = mouseMove;
         
         window.onload = function(){
            var canvases = document.getElementsByTagName('canvas');
            for (i in canvases) {
               disableSelection(canvases[i]);
            }
            var images = document.getElementsByTagName('img');
            for (i in images) {
               disableSelection(images[i]);
            }
            
            //##########- ADD ICON HERE (START) -##########//
            //canvasicon.addIcon(x,y,width,height,src);
/*            canvasicon.addIcon(100,100,100,100,"image/eraser.png");
            canvasicon.addIcon(100,200,100,100,"image/pencil.png");
            canvasicon.addIcon(100,250,100,100,"image/eraser.png");
            canvasicon.addIcon(200,100,100,100,"image/pencil.png");
            canvasicon.addIcon(200,200,100,100,"image/eraser.png");
            canvasicon.addIcon(200,300,100,100,"image/pencil.png");
            canvasicon.addIcon(300,100,100,100,"image/eraser.png");
            canvasicon.addIcon(300,200,100,100,"image/pencil.png");
            canvasicon.addIcon(300,300,100,100,"image/eraser.png");//*/
<?php $viewer->loadIcon();?>
            //##########- ADD ICON HERE  (END)  -##########//
            canvasimage.load("<?php $viewer->loadDataURL(); ?>");
            //canvasicon.refresh();
            
            try{
               setInterval(canvasicon.refresh, 30);
            }catch(ex){
               dump(ex);
            }
         };
         
         function mouseMove(e){
            mouse.x = e.pageX - DIMENSION.X;
            mouse.y = e.pageY - DIMENSION.Y;
         }
         function mouseDown(e){
            try{
            mouse.m = mouse.x;
            mouse.n = mouse.y;
            current.mousedown=true;
            
            if(!canvasdropbox.select()){
               //current.selectedicon=
               canvasicon.selectIcon();
               canvasicon.updateOffset();
               //canvasicon.moveIcon();
            }
            }catch(ex){alert(ex);}          
         }
         
         function mouseUp(e){
            current.mousedown=false;
         }
         
         var canvasdropbox = {
            clear:function(){
               var c = document.getElementById(CANVAS.DROPBOX).getContext("2d");
               c.clearRect(0,0,DIMENSION.WIDTH,DIMENSION.HEIGHT);
 
               canvasdropbox.drawn = -1;
               canvasdropbox.x = -1;
               canvasdropbox.y = -1;
               canvasdropbox.h = -1;
               canvasdropbox.w = -1;
               canvasdropbox.i = -1;
            },
            draw:function(i){
               var c = document.getElementById(CANVAS.DROPBOX).getContext("2d");
               c.clearRect(0,0,DIMENSION.WIDTH,DIMENSION.HEIGHT);
 
               if(i==-1) return;
               
               canvasdropbox.drawn = i;
               
 
               canvasdropbox.x = icons[i].x + icons[i].offsetX;
               canvasdropbox.y = icons[i].y + icons[i].offsetY;
 
               canvasdropbox.w = 200;
               canvasdropbox.i = 25;
 
               //prevents dropbox from appearing offscreen
               if(canvasdropbox.x + canvasdropbox.w > DIMENSION.WIDTH){
                  var offset = (canvasdropbox.x + canvasdropbox.w) - DIMENSION.WIDTH;
                  canvasdropbox.x -= offset;
               }
               if(canvasdropbox.y + (canvasdropbox.i*dropboxes[i].length) > DIMENSION.HEIGHT){
                  var offset = (canvasdropbox.y + (canvasdropbox.i*dropboxes[i].length)) - DIMENSION.HEIGHT;
                  canvasdropbox.y -= offset;
               }
 
 
               canvasdropbox.h = 0;
               for(d in dropboxes[i]){
                  canvasdropbox.h += canvasdropbox.drawItem(dropboxes[i][d],canvasdropbox.x,canvasdropbox.y + canvasdropbox.h, canvasdropbox.w, canvasdropbox.i);
               }
               
               c.beginPath();
               c.strokeStyle = "#000";
               c.lineWidth   = 2;
               c.moveTo(canvasdropbox.x + 0, canvasdropbox.y + 0);
               c.lineTo(canvasdropbox.x + canvasdropbox.w, canvasdropbox.y + 0);
               c.lineTo(canvasdropbox.x + canvasdropbox.w, canvasdropbox.y + canvasdropbox.h);
               c.lineTo(canvasdropbox.x + 0, canvasdropbox.y + canvasdropbox.h);
               c.lineTo(canvasdropbox.x + 0, canvasdropbox.y + 0);
               c.stroke();
 
               c.closePath();
            },
            drawItem:function(text,x,y,width,height){
               var c = document.getElementById(CANVAS.DROPBOX).getContext("2d");
               c.beginPath();
               if(mouse.x - x < width && mouse.x > x && mouse.y - y < height && mouse.y > y){
                  c.fillStyle = "#FFF";
               }else{
                  c.fillStyle = "#777";
               }
               c.fillRect(x,y,width,height);               
               c.fillStyle = "#000";
 
               c.fillText(text, x, y + 15, width );
               c.closePath();
               return height;
            },
            select:function(){ //return false if nothing selected.
               //this function determines if dropbox was clicked.
               if(canvasdropbox.drawn==-1)return false;
               if(mouse.x < canvasdropbox.x || mouse.x > canvasdropbox.x + canvasdropbox.w)return false;
               if(mouse.y < canvasdropbox.y || mouse.y > canvasdropbox.y + canvasdropbox.h)return false;
 
               //codes below determine which item was clicked and call the appropriate method.
               canvasdropbox.action(canvasdropbox.drawn,Math.floor((mouse.y - canvasdropbox.y)/canvasdropbox.i));
               canvasicon.clearSelection();
               return true;
            },
            action:function(i,j){//i is icon,j is item
               //dump("Item " + j + " of the dropbox from Icon " + i + " was clicked.");
               dump(dropboxlinks[i][j] + " is launched. [" + i + "," + j + "]");
            },
            drawn:-1,
            x:-1,
            y:-1,
            h:-1,
            w:-1,
            i:-1
         };
         
         var canvasicon = {
            refresh:function(){
               try{
                  var c = document.getElementById(CANVAS.ICON).getContext("2d");
                  c.clearRect(0,0,DIMENSION.WIDTH,DIMENSION.HEIGHT);
 
                  /*var selected = -1;
                  if(current.mousedown){
                     selected = canvasicon.selected;
                  }else{
                     selected = canvasicon.hoverIcon();
                  }*/
 
                  canvasdropbox.clear();
                  for (i in icons){
                     if(current.iconmovement == "bounce"){
                        //Change Direction for bounce action
                        if (icons[i].x + icons[i].dx > DIMENSION.WIDTH - icons[i].width || icons[i].x + icons[i].dx < 0)
                           icons[i].dx = -icons[i].dx;
                        if (icons[i].y + icons[i].dy > DIMENSION.HEIGHT - icons[i].height || icons[i].y + icons[i].dy < 0)
                           icons[i].dy = -icons[i].dy;
                     }
    
                     if(i == canvasicon.selected){
                        canvasdropbox.draw(i);
                     }else{
                        if(current.iconmovement == "bounce"){
                           //Movement for bounce action
                           icons[i].x += icons[i].dx;
                           icons[i].y += icons[i].dy;
                        }
                     }
                     canvasicon.drawIcon(icons[i]);
                  }
               }catch(ex){
                  dump(ex);
               }
            },
            drawIcon:function(icon){
               var c = document.getElementById(CANVAS.ICON).getContext("2d");
               var img = new Image();
               img.src = icon.src;
 
               if(current.iconmovement == "dance"){
                  //note: The '?' operator is used in assignment of variables.
                  //      Its use is as follow:
                  //          var = condition ? value if true : value if false ;
                  icon.dx = (icon.dx<0) ? icon.dx * -1 : icon.dx ;
                  icon.dy = (icon.dy<0) ? icon.dy * -1 : icon.dy ;
                  dx = Math.round((Math.random()*icon.dx*2)-icon.dx);
                  dy = Math.round((Math.random()*icon.dy*2)-icon.dy);
                  c.drawImage(img,icon.x+dx,icon.y+dy,icon.width,icon.height);
               }else{
                  c.drawImage(img,icon.x,icon.y,icon.width,icon.height);
               }
 
            },
            addIcon:function(x,y,width,height,src){
               var i = (Math.random()*10)-5;
               var j = (Math.random()*10)-5;
               icon = {x:x,y:y,width:width,height:height,src:src,dx:i,dy:j};
               icons.push(icon);
            },
            hoverIcon:function(){
               var list = new Array();
               for (i in icons){
                  if(mouse.x-icons[i].x<icons[i].width
                  && mouse.x-icons[i].x>0
                  && mouse.y-icons[i].y<icons[i].height
                  && mouse.y-icons[i].y>0){
                     list.push(i);
                  }
               }
               var tmp = list.pop();
               if(tmp>=0){
                  return tmp;
               }else{
                  return -1;
               }
            },
            selectIcon:function(){
               try{
                  canvasicon.selected = canvasicon.hoverIcon();
               }catch(ex){
                  alert(ex);
               }
            },
            /*updateIcon:function(iconIndex){
               icons[iconIndex].x=mouse.x-icons[iconIndex].offsetX;
               icons[iconIndex].y=mouse.y-icons[iconIndex].offsetY;
               canvasicon.refresh();
            },
            moveIcon:function(){
               //var selected = canvasicon.selectIcon();
               canvasicon.updateIcon(canvasicon.selected);
            },*/
            updateOffset:function(){
               try{
                  if(canvasicon.selected>=0){
                     icons[canvasicon.selected].offsetX=mouse.x-icons[canvasicon.selected].x;
                     icons[canvasicon.selected].offsetY=mouse.y-icons[canvasicon.selected].y;
                  }
               }catch(ex){
               }
            },//*/
            clearSelection:function(){
               canvasicon.selected = -1;
            },
            selected:-1
            
         };
         
         var canvasimage = {
            load:function(dataurl){
               var c = document.getElementById(CANVAS.IMAGE).getContext("2d");
               var img = new Image();
               img.onload = function(){
                  c.width = DIMENSION.WIDTH;
                  c.height = DIMENSION.HEIGHT;
                  c.drawImage(img,0,0);
               };
               img.src = dataurl;
            }
         };
         
         function disableSelection(element) {
            if (typeof element.onselectstart != 'undefined') {
               element.onselectstart = function() { return false; };
            }/* else if (typeof element.style.MozUserSelect != 'undefined') {
               element.style.MozUserSelect = 'none';
            }*/ else {
               element.onmousedown = function() { return false; };
            }
         }
 
         function dump(text){
            document.status.display.value=text;
         }
         
      </script> 
   </head> 
   <body> 
       <canvas id="canvasIcon" width="<?php echo $viewer->width;?>" height="<?php echo $viewer->height;?>" style="border:1px solid #c3c3c3;position:fixed;left:<?php echo $viewer->x;?>px;top:<?php echo $viewer->y;?>px;"> 
         Your browser  does not support the canvas element.
      </canvas> 
       <canvas id="canvasImage" width="<?php echo $viewer->width;?>" height="<?php echo $viewer->height;?>" style="border:1px solid #c3c3c3;position:fixed;left:<?php echo $viewer->x;?>px;top:<?php echo $viewer->y;?>px;"> 
         Your browser  does not support the canvas element.
      </canvas> 
      <canvas id="canvasDropBox" width="<?php echo $viewer->width;?>" height="<?php echo $viewer->height;?>" style="border:1px solid #c3c3c3;position:fixed;left:<?php echo $viewer->x;?>px;top:<?php echo $viewer->y;?>px;"> 
         Your browser  does not support the canvas element.
      </canvas> 
      <form name="status" style="position:fixed;top:<?php echo $viewer->height + 20;?>px;left:80px;"> 
      <input type="text" name="display" style="width:400px;"> 
      </form> 
   </body> 
</html> 
